package cn.xiaov.controller;

import cn.xiaov.domain.LoginUser;
import cn.xiaov.service.LoginUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpSession;
import java.util.List;

@Controller
@RequestMapping("/user")
public class LoginController {
    @Autowired
    LoginUserService loginUserService;

    @PostMapping("/login")
    public String login(LoginUser user, Model model, HttpSession session) {
        String username = user.getUsername();
        String password = user.getPassword();
        //用户名为空
        if (StringUtils.isEmpty(username)) {
            model.addAttribute("msg", "用户名为空");
            return "index";
        }
        //密码为空
        if (StringUtils.isEmpty(password)) {
            model.addAttribute("msg", "密码为空");
            return "index";
        }
        //有密码，有账号
        List<LoginUser> users = loginUserService.findByUserName(username);
        //用户名不存在
        if (users == null || users.size() == 0) {
            model.addAttribute("msg", "用户名不存在");
            return "index";
        }
        //超过1个
        if (users.size() > 1) {
            model.addAttribute("msg", "查询错误");
            return "index";
        }

        //  密码错误
        if (!password.equals(users.get(0).getPassword())) {
            model.addAttribute("msg", "密码错误");
            return "index";
        }
        //密码正确
        //将姓名添加到session域中
        session.setAttribute("loginUser",username);
        return "redirect:/main.html";
    }

    @RequestMapping("/logout")
    public String logout(HttpSession session){
        session.invalidate();
        return "redirect:/login.html";
    }
}
